package com.shiku.mpserver.service;

import cn.xyz.commons.support.mongo.MongoOperator;
import cn.xyz.commons.utils.ReqUtil;
import cn.xyz.mianshi.model.PageVO;
import cn.xyz.mianshi.utils.SKBeanUtils;
import cn.xyz.mianshi.vo.User;
import cn.xyz.repository.mongo.MongoRepository;
import com.google.common.collect.Lists;
import com.mongodb.*;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class MPServiceImpl implements MPService {


	//private MongoDatabase lastMsgDB;

	/**
	 * 单聊最后一条聊天记录  数据库
	 */
	private static final String LASTCHAT_DB = "shiku_lastChats";


	String getLastBody(int sender, int receiver) {
		MongoCollection<Document> mongoCollection = SKBeanUtils.getTigaseManager().getMongoCollection(SKBeanUtils.getTigaseManager().getLastMsgDB(), sender);
		Document q = new Document();
		q.put("userId", sender+"");
		q.put("jid", receiver+"");
		Document dbObj = mongoCollection.find(q).projection(new Document("content", 1))
		.sort(new Document("timeSend",-1)).first();
		if(null==dbObj)
			return null;
		return dbObj.get("content").toString();
	}

	/**
	 *  消息分组分页查询
	 */
	@Override
	public PageVO getMsgList(int userId, int pageIndex, int pageSize) {
		List<BasicDBObject> msgList = Lists.newArrayList();
		DBCollection dbCollection =SKBeanUtils.getTigaseManager().getCollection("shiku_msgs", userId);
		// 分组条件
		DBObject groupFileds = new BasicDBObject();
		groupFileds.put("receiver", "$receiver");
		// 过滤条件
		BasicDBObject map =new BasicDBObject();
		map.put("sender", userId+"");
		map.put("direction", 1);

		map.put("isRead", 0);
		DBObject macth=new BasicDBObject("$match",map);
		
		DBObject fileds = new BasicDBObject("_id", groupFileds);
		fileds.put("count", new BasicDBObject("$sum",1));
		DBObject group = new BasicDBObject("$group", fileds);
		DBObject limit=new BasicDBObject("$limit",pageSize);
		DBObject skip=new BasicDBObject("$skip",pageIndex*pageSize);
//		long total = dbCollection.find(new BasicDBObject("sender",userId+"").append("direction",1).append("isRead",0).put("s",new BasicDBObject("$sum",1))).count();
		long total =0;
		AggregationOutput out= dbCollection.aggregate(Arrays.asList(macth,group,skip,limit));
		List<DBObject> pipeline=new ArrayList<>();
		pipeline.add(macth);
		pipeline.add(group);
		AggregationOptions options=AggregationOptions.builder().build();
		Cursor cursor = dbCollection.aggregate(pipeline,options);
		while (cursor.hasNext()) {
			BasicDBObject dbObject = (BasicDBObject) cursor.next();
			total+=Long.valueOf(dbObject.get("count").toString());
		}
		System.out.println("分组后的数量 "+total);
		Iterable<DBObject> result=out.results();
		List<DBObject> list=(List<DBObject>) result;
		int sender =userId;
		int receiver=0;
		for(int i=0;i<list.size();i++){
			try {
				BasicDBObject dbObj=(BasicDBObject) list.get(i).get("_id");
				dbObj.append("count", list.get(i).get("count"));

				try {
					 receiver = Integer.valueOf(dbObj.getString("receiver"));
				} catch (Exception e) {

				}
				String nickname="";
				User user = SKBeanUtils.getUserManager().getUser(receiver);
				if(null!=user)
					nickname =user.getNickname();
				else
					continue;
				int count = dbObj.getInt("count");

				dbObj.put("nickname", nickname);
				dbObj.put("count", count);
				dbObj.put("sender", sender+"");
				dbObj.put("receiver", receiver+"");
				dbObj.put("body", getLastBody(sender, receiver));

				msgList.add(dbObj);
			} catch (cn.xyz.commons.ex.ServiceException e) {
				e.printStackTrace();
			}catch (Exception e) {
				e.printStackTrace();
			}
		}

//		return msgList;
		return new PageVO(msgList,total,pageIndex,pageSize);
	}




	public List<Document> queryLastChatList(long startTime, int pageSize){
		Integer userId = ReqUtil.getUserId();
		List<Document> resultList = Lists.newArrayList();

		BasicDBObject query=new BasicDBObject();
		if (0 != startTime)
			query.put("timeSend", new BasicDBObject("$lt", startTime));

		MongoCursor<Document> cursor =null;
		Document dbObj=null;

		query.append("userId", userId.toString());
		cursor=SKBeanUtils.getTigaseManager()
				.getMongoCollection(SKBeanUtils.getTigaseManager().getLastMsgDB(), userId).find(query)
				.sort(new Document("timeSend", -1)).limit(pageSize).iterator();
		try {
			while (cursor.hasNext()) {
				dbObj = cursor.next();
				if((int)dbObj.get("isRoom")!=1){
					String nickName = SKBeanUtils.getUserManager().getNickName(Integer.valueOf((String)dbObj.get("jid")));
					dbObj.put("toUserName",nickName);
				}
				resultList.add(dbObj);
			}
		} finally {
			if(null!=cursor)
				cursor.close();
		}

		return resultList;
	}



	@Override
	public Object getMsgList(int sender, int receiver, int pageIndex, int pageSize) {
		List<Document> msgList = Lists.newArrayList();
		MongoDatabase chatMsgDB = SKBeanUtils.getTigaseManager().getChatMsgDB();
		MongoCollection<Document> collection = MongoRepository.getCollection(chatMsgDB, sender);
		Document q = new Document();
		q.put("sender", sender+"");
		q.put("receiver", receiver+"");
		/*q.put("direction", 0);
		q.put("isRead", 0);*/

		MongoCursor<Document> iterator = collection.find(q).skip(pageIndex*pageSize).limit(pageSize).iterator();
		try {
			Document dbObj=null;
			while (iterator.hasNext()) {
				dbObj = iterator.next();
				dbObj.put("nickname", SKBeanUtils.getUserManager().getNickName(receiver));
				dbObj.put("content",dbObj.get("content").toString());
				msgList.add(dbObj);
			}
		} finally {
			if(null!=iterator)
				iterator.close();
		}
		return msgList;
	}

}
